package zct.proj;

import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.util.ArrayList;

import zct.proj.customView.MapDisp;
import zct.proj.customView.ViewScroll;
import zct.proj.util.ClientThread;
import zct.proj.util.CommUtil;
import zct.proj.util.Const;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.KeyguardManager;
import android.app.KeyguardManager.KeyguardLock;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.res.AssetFileDescriptor;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.Spinner;

public class ZctActivity extends Activity {
	
	boolean skipFinish;
	
//	PhotoSortrView photoSorter;

//	@Override
//	public void onPause() {
////		Log.v("MapAct", "onPause");
//		super.onPause();
//		if (!skipFinish) {
//			finish();
//		} else {
//			skipFinish = false;
//		}
////		finish();
////	    Intent intent = new Intent(MapActivity.this, ZctActivity.class);
////	    setResult(RESULT_OK, intent);
////	    stationView.endAllTask();
////	    stationView = null;
////	    MapActivity.this.finish();
//	    
//	}
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		
//		KeyguardManager keyguardManager = (KeyguardManager)getSystemService(Activity.KEYGUARD_SERVICE);
//		KeyguardLock lock = keyguardManager.newKeyguardLock(KEYGUARD_SERVICE);
//		lock.disableKeyguard();
		super.onCreate(savedInstanceState);
		setLockPatternEnabled(true);
		
		
//		this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE);
//		this.setTitle(R.string.instructions);
//		photoSorter = new PhotoSortrView(this);
//		PhotoSortrView md = new PhotoSortrView(this);
//		setContentView(md);
//		setContentView(photoSorter);
		setContentView(R.layout.main);
		ArrayList<String> sList = CommUtil.getStations();
		ArrayAdapter<String> aa = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, sList);
		Spinner sp = (Spinner) this.findViewById(R.id.stationList);
		sp.setAdapter(aa);
		String lastStation = CommUtil.getSetting(this, "lastStation");
		if (lastStation != null && sList.contains(lastStation)) {
			sp.setSelection(sList.indexOf(lastStation), true);
		}
		
		Button b = (Button) this.findViewById(R.id.btnStart);
		b.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(ZctActivity.this, MapActivity.class);
				Spinner sp = (Spinner) ZctActivity.this.findViewById(R.id.stationList);
				intent.putExtra(Const.KEY_STATION_NAME, sp.getSelectedItem().toString());
				skipFinish = true;
				startActivityForResult(intent, 0);
				CommUtil.saveSetting(ZctActivity.this, "lastStation", sp.getSelectedItem().toString());
			}
		});
		
		
//		String telSaved = getSetting("tel");
		TelephonyManager tm = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
		String telRead = tm.getLine1Number();
	    // 手机号码不正确或没取到
	    if (telRead != null && !"".equals(telRead)) {
		    // 读取到号码
		    CommUtil.saveSetting(this, "tel", telRead);
	    } else {
		    // 无号码信息，提示输入手机号
	    	String telSaved = CommUtil.getSetting(this, "tel");
	    	if (telSaved == null || telSaved.equals("")) {
	    		showInputTelAlert(null);
	    	}
	    }
	}
	
	private void showInputTelAlert(String telDefault) {
		final EditText telnum = new EditText(this);
		if (telDefault != null) {
			telnum.setText(telDefault);
		}
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("请输入手机号码").setView(telnum);
		builder.setPositiveButton("确定", new android.content.DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				CommUtil.saveSetting(ZctActivity.this, "tel", telnum.getText().toString());
				Log.v("zct act", telnum.getText().toString());
			}
		}).setNegativeButton("取消", null).show();  
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (resultCode) {
		case RESULT_OK:
			finish();
			break;
		default:
			break;
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
		
        // 设置屏幕亮度
		float bri = CommUtil.getBrightness();
		if (bri > 0) {
			WindowManager.LayoutParams layoutParams = this.getWindow().getAttributes();
			layoutParams.screenBrightness = bri;
			// 重新设置窗口的属性
	        this.getWindow().setAttributes(layoutParams);
		}
	}

//	@Override
//	protected void onPause() {
//		super.onPause();
////	photoSorter.unloadImages();
//	}
	

        
    public void setLockPatternEnabled(boolean enabled) {
    	getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        setBoolean(android.provider.Settings.System.LOCK_PATTERN_ENABLED,
                enabled);
    }
    private void setBoolean(String systemSettingKey, boolean enabled) {
        android.provider.Settings.System.putInt(getContentResolver(),
                systemSettingKey, enabled ? 1 : 0);
    }
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		//menu.add(Menu.NONE, Menu.FIRST + 1, 2, "退出").setIcon(android.R.drawable.ic_menu_save);
		menu.add(Menu.NONE, Menu.FIRST + 2, 1, "设置号码").setIcon(R.drawable.menu_gear);
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		super.onOptionsItemSelected(item);
		switch (item.getItemId()) {
		case Menu.FIRST + 1:
			finish();
			break;
		case Menu.FIRST + 2:
			showInputTelAlert(CommUtil.getSetting(ZctActivity.this, "tel"));
			break;
		}
		return true;
	}

//	@Override
//	public boolean onKeyDown(int keyCode, KeyEvent event) {
//	if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
//	photoSorter.trackballClicked();
//	return true;
//	}
//	return super.onKeyDown(keyCode, event);
//	}


	
	
	
	
	
//	float ex, ey, ox, oy;
//	ViewScroll vs;
//	MapDisp md;
//	ArrayList<String> playList = new ArrayList<String>();
//	private MediaPlayer mp;
//	boolean playing = false;
//	Button btnUp, btnDown, btnLeft, btnRight, btnZoomIn, btnZoomOut, btnB;
////	ClientThread cThread = null;
//	
//	OnClickListener btnClickListener = new OnClickListener() {
//		
//		public void onClick(View v) {
////			SurfaceHolder sh = md.getHolder();
////			Canvas canvas = sh.lockCanvas(new Rect(100, 100, 200, 200));
////			canvas.save();
////			canvas.rotate(30, 150, 150);
////			Paint paint = new Paint();
////			paint.setColor(Color.RED);
////			canvas.drawRect(110, 110, 150, 150, paint);
////			canvas.restore();
////			paint.setColor(Color.GREEN);
////			canvas.drawRect(150, 150, 190, 190, paint);
////			sh.unlockCanvasAndPost(canvas);
//			if (v == btnUp) {
////				md.layout(md.getLeft(), md.getTop() - 50, md.getRight(), md.getBottom() - 50);
//				
//				// socket客户端的事件处理
////				Socket s;
//				handler = new Handler() {
//					@Override
//					public void handleMessage(Message msg) {
//						if (msg.what == Const.MSG_PLAY_SOUND) {
//							// 来自socket的通知
//							String sList = msg.getData().getString(Const.MSG_HND);
//							// 添加播放列表
//							addNewPlayTaskToPlayList(sList);
//							// 播放声音
//							playSound();
////							Log.v("activity", "play sound for : " + sList);
//						} else if (msg.what == Const.MSG_SWITHCER_CHANGED) {
//							int[] list = msg.getData().getIntArray(Const.MSG_HND);
//							md.drawChanged(list);
//						} else if (msg.what == Const.MSG_STATION_DATA) {
//							md.setStationInitData(msg.getData().getIntArray(Const.MSG_HND));
//							md.drawChanged(new int[]{});
//						}
//					}
//				};
//				try {
//					new Thread(new ClientThread(handler)).start();
//				} catch (IOException e) {
//					e.printStackTrace();
//				}
//			} else if (v == btnDown) {
//				md.showLog();
////				playSound();
////				cThread.send();
////				md.layout(md.getLeft(), md.getTop() + 50, md.getRight(), md.getBottom() + 50);
//			} else if (v == btnLeft) {
//				md.layout(md.getLeft() - 50, md.getTop(), md.getRight() - 50, md.getBottom());
//			} else if (v == btnRight) {
//				md.layout(md.getLeft() + 50, md.getTop(), md.getRight() + 50, md.getBottom());
//			} else if (v == btnZoomIn) {
//				md.Zoom(1.1f);
//			} else if (v == btnZoomOut) {
//				md.Zoom(0.9f);
//			} else if (v == btnB) {
////				md.drawSome();
//				vs.setTVClick();
//			}
//		}
//	};
//	
//	private void addNewPlayTaskToPlayList(String playString) {
//		
//		String path = "Female";
//		if (playString.startsWith("SX")) {
//			path = "Male";
//		}
//		if (playString != null) {
//			String[] sounds = playString.split(",");
//			for (String sound : sounds) {
//				if (sound != null && sound.length() > 0) {
//					playList.add(path + "/" + sound + ".wav");
//				}
//			}
//			// 添加空行，代表本段结束
//			playList.add(null);
//		}
//	}
//	
//	private void playSound() {
//		Log.v("play", "play sound called and now is " + (playing ? "1": "0"));
//		if (!playing && playList.size() > 0) {
////			mp = new MediaPlayer();
//			String file = playList.get(0);
//			if (file == null) {
//				playList.remove(0);
//				if (playList.size() > 0) {
//					try {
////						Log.v("play", "sleep 1000ms");
//						Thread.sleep(1000);
//					} catch (InterruptedException e) {
//						e.printStackTrace();
//					}
//				}
//			}
//			
//			if (playList.size() > 0) {
//				try {
//					playing = true;
//					mp.reset();
//					AssetFileDescriptor afd;
//					afd = getAssets().openFd("sound/" + playList.get(0));
//					long start = afd.getStartOffset();
//					long end = afd.getLength();
//					mp.setDataSource(afd.getFileDescriptor(), start,end);
//					mp.prepare();
//					mp.start();
////					Log.v("play", "play sound");
//				} catch (IOException e) {
//					e.printStackTrace();
//				}
//			}
//		}
//	}
//    
//	Handler handler;
//    /** Called when the activity is first created. */
//    @Override
//    public void onCreate(Bundle savedInstanceState) {
//        super.onCreate(savedInstanceState);
//        setContentView(R.layout.main);
//        
//        mp = new MediaPlayer();
//        mp.setOnCompletionListener(new OnCompletionListener() {
//			public void onCompletion(MediaPlayer mp) {
////				Log.v("play", "play finished.");
//				playing = false;
//				playList.remove(0);
//				playSound();
//			}
//		});
//        
//        LinearLayout bk = (LinearLayout) findViewById(R.id.bk);
//        LinearLayout btnList = (LinearLayout) findViewById(R.id.btnList);
//		btnUp = new Button(this);
//		btnUp.setText("up");
//		btnUp.setOnClickListener(btnClickListener);
//		btnList.addView(btnUp, 100, 50);
//		btnDown = new Button(this);
//		btnDown.setText("down");
//		btnDown.setOnClickListener(btnClickListener);
//		btnList.addView(btnDown, 100, 50);
//		btnLeft = new Button(this);
//		btnLeft.setText("left");
//		btnLeft.setOnClickListener(btnClickListener);
//		btnList.addView(btnLeft, 100, 50);
//		btnRight = new Button(this);
//		btnRight.setText("right");
//		btnRight.setOnClickListener(btnClickListener);
//		btnList.addView(btnRight, 100, 50);
//		btnZoomIn = new Button(this);
//		btnZoomIn.setText("bigger");
//		btnZoomIn.setOnClickListener(btnClickListener);
//		btnList.addView(btnZoomIn, 100, 50);
//		btnZoomOut = new Button(this);
//		btnZoomOut.setText("smaller");
//		btnZoomOut.setOnClickListener(btnClickListener);
//		btnList.addView(btnZoomOut, 100, 50);
//		btnB = new Button(this);
//		btnB.setText("GO");
//		btnB.setOnClickListener(btnClickListener);
//		btnList.addView(btnB, 100, 50);
//		
//		vs = new ViewScroll(this);	
//		bk.addView(vs, 1500, 700);
//		
//		md = new MapDisp(this);
//		vs.addView(md, 1500, 700);
//    }
}

